import { getMenuByRoute } from "@utils";
import {getStringSet} from "@utils/dataStruct";

import _ from "lodash";
export default class NavManager {
    constructor(vm, { onUpdate, max = 20 } = {}) {
        this.vm = vm;
        // this.navTabList = [
        //     { fullPath: "/", name: "main", meta: { title: "首页" } },
        // ];

        // this.updateStateHandle([ //此处有点坑，注释
        //     { fullPath: "/", name: "main", meta: { title: "首页" } },
        // ]);

        this.onUpdate = onUpdate;
        this.maxTabNumber = max;
   
        vm.$router.afterEach((to, from) => {
            this.saveToList(to);
        });

        this.vm.$nextTick(() => {
            this.saveToList(vm.$route);
        });
    }

    getNavTabList() {
        return this.vm.$store.state.global.navTabList;
    }

    saveToList(to) {

            //console.log(to,'----tototototo')
       
            let navTabList = this.getNavTabList();
            let tabTitle=to.tabTitle;
   
            let menuList = this.vm.$store.state.account.menuList;
            let menuPath = getMenuByRoute(to, menuList);
            let activePath = _.get(menuPath, `[${menuPath.length - 1}]`) || [];
                tabTitle = _.get(activePath, `[${activePath.length - 1}].name`);
    
            const titleSet = getStringSet(to.meta.title); // :Object;
            if(!_.isEmpty(titleSet)) {
                const title = to.query[titleSet["titleKey"]];
                tabTitle = title ? title : tabTitle;
            }
            if(!tabTitle) {
                tabTitle = to.query[to.query.titleKey] || ""
            }
        const repeatPage = to.meta.repeatPage;

        if(to.params?.tabTitle){
           
            if(to.params?.wrkfmId && to.params?.wrkfmId!=''){
                tabTitle=to.params?.wrkfmId;
            }else{
                tabTitle=to.params?.tabTitle;
            }
            // if(to.query.path=='/cmsfront/#/'){
            //     tabTitle=''
            // }
        }

        let deOptions=decodeURIComponent(to.fullPath)
        // let isTrue=deOptions.search('workOrderDetail')//投诉工单详情多开数字标题
        // if(isTrue>-1){
        //     let index=deOptions.lastIndexOf('\/');
        //     let str=deOptions.substring(index+1,deOptions.length);
        //     tabTitle=str 
        // }
        //console.log(tabTitle,'----tabTitletabTitletabTitle')
        to = {
            fullPath: to.fullPath,
            hash: to.hash,
            meta: to.meta,
            name: to.name,
            query: to.query,
            path: to.path,
            // tabTitle: to.tabTitle,
            tabTitle,
            matched: to.matched,
            repeatPage
        };
        let fullPath = to.fullPath;
        
        if (to.name === "iframe" && !tabTitle) {
            const updateTitle = () => {
                let iframe = document.querySelector(
                    `iframe[src="${to.query.path}"]`
                );
                if (iframe&&iframe.contentDocument)
                to.tabTitle = iframe.contentDocument&&iframe.contentDocument.title;
                this.updateStateHandle();
            };
            setTimeout(updateTitle, 1000);
            setTimeout(updateTitle, 5000);
            setTimeout(updateTitle, 8000);
        }

        let matchedIndex = navTabList.findIndex((v, i) => {
            if(to.name === 'iframe' || to.repeatPage) {
                return v.fullPath === fullPath;
            }else {
                return to.name && to.name === v.name || to.fullPath === v.fullPath;
            }
        });

        if (matchedIndex === -1) {
            navTabList.push(to);

            this.updateStateHandle();
        } else {
            navTabList.splice(matchedIndex, 1, to);

            this.updateStateHandle();
        }
    }

    getActivedFullPath() {
        return this.vm.$route.fullPath;
    }

    jumpTo(options) {

        console.log('jumpTo---', options)
        let fullPath = options;
        // 判断是否超出最大缓存页数
        let navTabList = this.getNavTabList() || [];
        let max = 3;
        //console.log(options, "---jumpTo");
        if (typeof options === "object") {
            fullPath = options.fullPath;
            let tabTitle=options?.tabTitle||'';
            let params=options.params||{};
            Object.assign(params,{tabTitle});
            options.params=params;
        }
        // if(!navTabList.some(item => item.fullPath === fullPath)) {
        //     if (navTabList.length > max) {
        //         let removeItem = navTabList.slice(1, 2)[0];
        //         if (removeItem) {
        //             this.removeItem(removeItem.fullPath)
        //         }
        //     }
        // }

        if (fullPath !== this.getActivedFullPath()) {
            //console.log(options,'optionsoptionsoptions333')
            this.vm.$router.push(options);
        }
    }

    jumpToBefore(index) {
        let navTabList = this.getNavTabList();
        if (navTabList[index - 1]) {
            this.jumpTo(navTabList[index - 1].fullPath);
            return;
        }
        this.jumpTo({ name: "main" });
    }

    removeItem(fullPath) {
        let navTabList = this.getNavTabList();
        for (let index = 0; index < navTabList.length; index++) {
            const tab = navTabList[index];

            if (tab.fullPath === fullPath) {
                navTabList.splice(index, 1);
                if (fullPath === this.getActivedFullPath()) {
                    this.jumpToBefore(index);
                }
                this.updateStateHandle();
                break;
            }
        }
    }

    removeAll() {
        let navTabList = this.getNavTabList() || [];
        [...navTabList].forEach(item => {
            if(item.fullPath !== '/') {
                this.removeItem(item.fullPath);
            }
        })
    }

    removeOther(path) {
        let navTabList = this.getNavTabList() || [];

        [...navTabList].forEach(item => {
            if(!['/', path].includes(item.fullPath)) {
                this.removeItem(item.fullPath);
            }
        })
    }

    updateStateHandle(list) {
        // this.onUpdate && this.onUpdate();
        if (!list) {
            list = this.getNavTabList();
        }
        this.vm.$store.commit("global/SET_NAV_TAB_LIST", [...list]);
    }
}
